package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.dto.VehicleSearchRequest;
import com.zhentao.pojo.VehicleInfo;
import com.zhentao.service.VehicleInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 车辆信息控制器
 */
@RestController
@RequestMapping("/api/vehicle")
@CrossOrigin
public class VehicleController {

    @Autowired
    private VehicleInfoService vehicleInfoService;

    /**
     * 搜索车辆信息
     */
    @PostMapping("/search")
    public Result<Map<String, Object>> searchVehicles(@RequestBody VehicleSearchRequest request) {
        try {
            if (!StringUtils.hasText(request.getKeyword())) {
                return Result.badRequest("搜索关键词不能为空");
            }

            // 创建分页对象
            Page<VehicleInfo> page = new Page<>(request.getPageNum(), request.getPageSize());
            
            // 构建查询条件
            QueryWrapper<VehicleInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1); // 只查询正常状态的车辆
            
            String keyword = request.getKeyword().trim();
            String searchType = request.getSearchType();
            
            if ("LICENSE_PLATE".equals(searchType)) {
                // 车牌号精确搜索
                queryWrapper.like("license_plate", keyword);
            } else if ("OWNER_NAME".equals(searchType)) {
                // 车主姓名模糊搜索
                queryWrapper.like("owner_name", keyword);
            } else if ("OWNER_PHONE".equals(searchType)) {
                // 车主电话模糊搜索
                queryWrapper.like("owner_phone", keyword);
            } else {
                // 全字段搜索
                queryWrapper.and(wrapper -> wrapper
                    .like("license_plate", keyword)
                    .or().like("owner_name", keyword)
                    .or().like("owner_phone", keyword)
                    .or().like("brand", keyword)
                    .or().like("model", keyword)
                    .or().like("color", keyword)
                );
            }
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc("create_time");
            
            // 执行分页查询
            IPage<VehicleInfo> result = vehicleInfoService.page(page, queryWrapper);
            
            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("records", result.getRecords());
            data.put("total", result.getTotal());
            data.put("current", result.getCurrent());
            data.put("size", result.getSize());
            data.put("pages", result.getPages());
            
            return Result.success("搜索成功", data);
            
        } catch (Exception e) {
            return Result.error("搜索失败：" + e.getMessage());
        }
    }

    /**
     * 根据车牌号获取车辆详情
     */
    @GetMapping("/detail/{licensePlate}")
    public Result<VehicleInfo> getVehicleDetail(@PathVariable String licensePlate) {
        try {
            QueryWrapper<VehicleInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("license_plate", licensePlate);
            queryWrapper.eq("status", 1);
            
            VehicleInfo vehicle = vehicleInfoService.getOne(queryWrapper);
            
            if (vehicle != null) {
                return Result.success("查询成功", vehicle);
            } else {
                return Result.notFound("未找到车辆信息");
            }
            
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据车牌号获取车辆信息（供其他服务调用）
     */
    public VehicleInfo getByLicensePlate(String licensePlate) {
        QueryWrapper<VehicleInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("license_plate", licensePlate);
        queryWrapper.eq("status", 1);
        return vehicleInfoService.getOne(queryWrapper);
    }

    /**
     * 根据ID获取车辆详情
     */
    @GetMapping("/detail/id/{id}")
    public Result<VehicleInfo> getVehicleById(@PathVariable Long id) {
        try {
            VehicleInfo vehicle = vehicleInfoService.getById(id);
            
            if (vehicle != null && vehicle.getStatus() == 1) {
                return Result.success("查询成功", vehicle);
            } else {
                return Result.notFound("未找到车辆信息");
            }
            
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取热门搜索关键词
     */
    @GetMapping("/hot-keywords")
    public Result<Object> getHotKeywords() {
        try {
            // 这里可以实现热门搜索关键词的逻辑
            // 暂时返回一些示例数据
            String[] hotKeywords = {
                "丰田", "本田", "大众", "奔驰", "宝马", 
                "年检", "保养", "维修", "京A", "京B"
            };
            
            return Result.success("获取成功", hotKeywords);
            
        } catch (Exception e) {
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 搜索建议（自动补全）
     */
    @GetMapping("/suggest")
    public Result<Object> getSearchSuggestions(@RequestParam String keyword,
                                             @RequestParam(defaultValue = "5") Integer limit) {
        try {
            if (!StringUtils.hasText(keyword) || keyword.trim().length() < 2) {
                return Result.success("关键词太短", new String[0]);
            }
            
            QueryWrapper<VehicleInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1);
            queryWrapper.and(wrapper -> wrapper
                .like("license_plate", keyword.trim())
                .or().like("owner_name", keyword.trim())
                .or().like("brand", keyword.trim())
                .or().like("model", keyword.trim())
            );
            queryWrapper.last("LIMIT " + limit);
            
            // 这里可以优化为只返回建议的关键词，而不是完整的车辆信息
            return Result.success("获取成功", vehicleInfoService.list(queryWrapper));
            
        } catch (Exception e) {
            return Result.error("获取建议失败：" + e.getMessage());
        }
    }
}